package org.example.backend.utils;
/*
 * @Date 2024-10-04
 * @Author 28254
 * @ClassName Captcha
*/

import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.context.request.WebRequest;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;
@Component
public class Captcha {
    // 宽度
    private static final Integer WIDTH = 100;
    // 高度
    private static final Integer HEIGHT = 30;
    // 字符数量
    private static final Integer CODE_LENGTH = 4;
    // 干扰线
    private static final Integer LINES = 16;
    private static final String CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

    /**
     * 获取验证码
     * @return 返回生成内容 字符串类型
     */
    private String getCaptchaText(){
        StringBuilder captchaText = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < CODE_LENGTH; i++) {
            captchaText.append(CHARS.charAt(random.nextInt(CHARS.length())));
        }
        return captchaText.toString();
    }
    public void getCaptchaImage(WebRequest request, HttpServletResponse response) throws IOException {
        // 设置响应类型
        response.setContentType("image/jpeg");
        // 生成验证码
        String code = this.getCaptchaText();
        // 保存验证码到 session
        HttpSession session = ((ServletWebRequest) request).getRequest().getSession();
        session.setAttribute("captcha", code);
        // 创建图像缓冲区
        BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
        Graphics2D graphics = image.createGraphics();
        // 设置背景颜色,填充
        graphics.setColor(Color.WHITE);
        graphics.fillRect(0, 0, WIDTH, HEIGHT);
        // 设置边框
        graphics.setColor(Color.GRAY);
        graphics.drawRect(0, 0, WIDTH-1, HEIGHT-1);
        // 设置字体
        graphics.setFont(new Font("Arial",Font.BOLD,20));
        // 设置随机干扰线
        for(int i = 0; i < LINES; i++){
            graphics.setColor(this.getRandomColor());
            graphics.drawLine(new Random().nextInt(WIDTH),new Random().nextInt(HEIGHT),
                    new Random().nextInt(WIDTH),new Random().nextInt(HEIGHT));
        }
        // 绘制验证码文本内容
        graphics.setColor(Color.BLACK);
        graphics.drawString(this.getCaptchaText(), WIDTH/5, 20);
        // 释放资源
        graphics.dispose();
        // 将图像写入响应流
        ImageIO.write(image,"JPEG",response.getOutputStream());
    }
    // 设置随机颜色
    private Color getRandomColor(){
        Random random = new Random();
        return new Color(random.nextInt(256), random.nextInt(256), random.nextInt(256));
    }
}
